package com.shangxia.lucky.lucky.job.write;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.shangxia.lucky.lucky.ConfigText;
import com.shangxia.lucky.lucky.common.FactoryHead;
import com.shangxia.lucky.lucky.writeHandler.MyTrueWriteHandler;
import com.shangxia.lucky.lucky.writeHandler.MyTypeThreadWriteHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;

import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * @author zhouya38158
 * @date 2021/11/16 14:50
 *
 */
@Slf4j
public class MatchColumnWriterThread implements Runnable, ExportThreadJobOver {

    public volatile Boolean MatchColumnWriterThread_FLAG = Boolean.FALSE;
    public final static LinkedList<List<List<String>>> columnQueue = new LinkedList<>();
    private ConfigText configText;
    private Integer headLength;

    public MatchColumnWriterThread(ConfigText configText, Integer headLength) {
        this.configText = configText;
        this.headLength = headLength;
    }

    @Override
    public Boolean over() {
        return MatchColumnWriterThread_FLAG;
    }

    @Override
    public void run() {
        WriteSheet columnSheet = EasyExcel.writerSheet("tongji")
                .registerWriteHandler(new MyTrueWriteHandler())
                .head(FactoryHead.headLength(headLength)).build();
        String file = configText.getBananaAbsoluteResultPath() + DateFormatUtils.format(new Date(), "yyyy-MM-dd_H-mm-ss") + "列统计.xlsx";
        ExcelWriter excelWriter = EasyExcel.write(file).build();
        log.info("结果输出 开始");
        int count = 0;

        while (!over() || !columnQueue.isEmpty()) {
            List<List<String>> columnLists = columnQueue.poll();
            if (null != columnLists) {
                if (count++ % 1000 == 0) {
                    log.info("输出结果第" + count + "行");
                }
                excelWriter.write(columnLists, columnSheet);
            }
        }
        excelWriter.finish();
        log.info("-----MatchColumnWriterThread-----结果输出结束----------------");
    }

    public void stop() {
        MatchColumnWriterThread_FLAG = true;
    }
}
